﻿using System;
using System.ComponentModel.DataAnnotations;
using Nxg.Blog.Core.Documents;

namespace Nxg.Blog.Core.Commands.Posts {
    public class NewCommentCommand {
        public SpamShield SpamShield { get; set; }

        public int PostId { get; set; }

        public string TitleSlug { get; set; }

        [Required]
        public string NickName { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        public string SiteUrl { get; set; }

        [Required]
        [MinLength (3)]
        public string Content { get; set; }

        public string IPAddress { get; set; }
    }

    public class NewCommentCommandInvoker : ICommandInvoker<NewCommentCommand, CommandResult> {
        private readonly DataContext _db;
        private readonly ISpamShieldService _spamShield;

        public NewCommentCommandInvoker (DataContext db, ISpamShieldService spamShield) {
            _db = db;
            _spamShield = spamShield;
        }

        public CommandResult Execute (NewCommentCommand command) {
            if (_spamShield.IsSpam (command.SpamShield)) {
                return new CommandResult ("You are a spam!");
            }

            var comment = new BlogComment {
                Email = command.Email,
                NickName = command.NickName,
                Content = command.Content,
                IPAddress = command.IPAddress,
                PostId = command.PostId,
                SiteUrl = command.SiteUrl,
                CreatedTime = DateTime.Now
            };
            _db.Comment.Add (comment);
            _db.SaveChanges ();
            return CommandResult.SuccessResult;
        }
    }
}